package com.binguo.service;

import com.binguo.common.util.LoggerUtil;
import com.binguo.entity.DiscountOrderDetail;
import com.binguo.model.model.DiscountOrder;
import com.binguo.model.mapper.*;
import com.binguo.model.model.CustomerExtend;
import com.binguo.model.model.ShopConfigExtend;
import com.binguo.model.model.ShopDiscount;
import com.binguo.model.model.ShopHoursConfig;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class NewDiscountService {

    static Map<Integer, Integer> dayOfWeekMap = new HashMap<>();
    static {
        dayOfWeekMap.put(1, 7);
        dayOfWeekMap.put(2, 1);
        dayOfWeekMap.put(3, 2);
        dayOfWeekMap.put(4, 3);
        dayOfWeekMap.put(5, 4);
        dayOfWeekMap.put(6, 5);
        dayOfWeekMap.put(7, 6);
    }

    @Resource
    private DiscountMapper discountMapper;

    @Resource
    private CustomerExtendMapper customerExtendMapper;

    @Resource
    private PayCardMapper payCardMapper;

    @Resource
    private ShopHoursConfigMapper shopHoursConfigMapper;
    @Resource
    private ShopConfigExtendMapper shopConfigExtendMapper;
    @Resource
    private DiscountOrderMapper discountOrderMapper;

    public void deleteAllDiscountOrder(){
        discountOrderMapper.deleteAllDiscountOrder();
    }

    public DiscountOrderDetail discount(Integer shopId, Integer customerId, Long totleFee, Integer userGroupId){
        DiscountOrderDetail discountOrder = new DiscountOrderDetail();
        //查询优惠信息
        List<ShopDiscount> shopDiscount = discountMapper.selectListByShopId(shopId);
        Integer groupID = null;

        if (shopDiscount != null && shopDiscount.size() > 0) {
            for (ShopDiscount discount : shopDiscount) {
                if (discount == null) {
                    return null;
                }
            }

            if (userGroupId == null) {
                Condition condition = new Condition(CustomerExtend.class);
                condition.or().andEqualTo("shopId", shopId)
                        .andEqualTo("customerId", customerId);
                List<CustomerExtend> customerExtendList = customerExtendMapper.selectByCondition(condition);
                if (customerExtendList != null && customerExtendList.size() > 0) {
                    CustomerExtend customerExtend = customerExtendList.get(0);

                    userGroupId = customerExtend.getGroupId();

                    LoggerUtil.console.info("userGroupId=={}", userGroupId);
                }
            }

            if (userGroupId == null) {
                return null;
            }

            ShopDiscount currentShopDiscount = null;

            for (ShopDiscount temp : shopDiscount) {
                String userGroupList = temp.getUserGroupIdList();

                if (userGroupList.equals("-1")) {
                    //全部分组
                    currentShopDiscount = temp;
                } else {
                    if (userGroupList.contains(",")) {
                        String[] userGroupArray = userGroupList.split(",");
                        for (String uga : userGroupArray) {
                            if (uga.equals(userGroupId.toString())) {
                                currentShopDiscount = temp;
                            }
                        }
                    } else {
                        if (userGroupList.equals(userGroupId.toString())) {
                            currentShopDiscount = temp;
                        }
                    }
                }
            }

            if (currentShopDiscount == null) {
                return null;
            }
            //查询授权
            if (StringUtils.hasText(currentShopDiscount.getProductCategoryIdList())) {
                if ("-1".equals(currentShopDiscount.getProductCategoryIdList())) {//1、全部菜品
                    boolean allowed = false;

                    boolean timeAllow = false;

                    String discountTime = currentShopDiscount.getDiscountTime();

                    if ("-1".equals(discountTime)) {//3、全部时间
                        timeAllow = true;
                    } else if (StringUtils.hasText(discountTime)) {
                        //3、优惠时间,周几
                        int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
                        String chineseDayOfWeek = String.valueOf(dayOfWeekMap.get(dayOfWeek));

                        LoggerUtil.console.info("chineseDayOfWeek=={}", chineseDayOfWeek);
                        if (discountTime.contains(",")) {
                            String[] discountTimeArray = discountTime.split(",");
                            for (String s : discountTimeArray) {
                                if (s.equals(chineseDayOfWeek)) {
                                    timeAllow = true;
                                    break;
                                }
                            }
                        } else {
                            if (discountTime.equals(chineseDayOfWeek)) {
                                timeAllow = true;
                            }
                        }
                    }


                    if (timeAllow) {
                        boolean periodAllow = false;
                        String discountPeriod = currentShopDiscount.getDiscountPeriod();

                        LoggerUtil.console.info("discountPeriod=={}", discountPeriod);
                        if ("-1".equals(discountPeriod)) {//4。全部时段
                            periodAllow = true;
                        } else if (StringUtils.hasText(discountPeriod)) {
                            if (discountPeriod.contains(",")) {
                                String[] disPeriodArray = discountPeriod.split(",");

                                for (String s : disPeriodArray) {
                                    periodAllow = isPeriodAllow(s);

                                    if (periodAllow == true) {
                                        break;
                                    }
                                }
                            } else {
                                periodAllow = isPeriodAllow(discountPeriod);
                            }
                        }

                        if (periodAllow) {
                            boolean ruleAllow = false;
                            Integer discountType = currentShopDiscount.getDiscountType();
                            Integer rule = currentShopDiscount.getRule();
                            Integer value = currentShopDiscount.getValue();
                            Integer ruleType = currentShopDiscount.getRuleType();

                            if (discountType != null) {//1:满折 2:满减
                                if (totleFee >= rule) {
                                    ruleAllow = true;
                                }
                            }

                            long resultFee = 0;

                            if (ruleAllow) {
                                Condition scec = new Condition(ShopConfigExtend.class);
                                scec.or().andEqualTo("shopId", shopId);
                                List<ShopConfigExtend> shopConfigExtendList = shopConfigExtendMapper.selectByCondition(scec);

                                ShopConfigExtend shopConfigExtend = null;
                                if (shopConfigExtendList != null && shopConfigExtendList.size() > 0) {
                                    shopConfigExtend = shopConfigExtendList.get(0);
                                }
                                Integer discountHandleType = null;
                                Integer discountPriceUnit = null;
                                if (shopConfigExtend != null) {
                                    discountPriceUnit = shopConfigExtend.getDiscountPriceUnit();
                                    discountHandleType = shopConfigExtend.getDiscountHandleTyp();
                                }

                                if (discountType == 1) {//1:满折 2:满减
                                    BigDecimal subFee = new BigDecimal(totleFee * (100 - value)).divide(new BigDecimal(100));//单位分

                                    if (subFee.intValue() > currentShopDiscount.getDiscountTop()) {//封顶金额配置
                                        subFee = new BigDecimal(currentShopDiscount.getDiscountTop());
                                    }

                                    resultFee = totleFee - subFee.longValue();
                                } else if (discountType == 2) {//2:满减
                                    long subFee = 0;
                                    if (ruleType != null) {
                                        if (ruleType == 1) {//1:每满 2:总满
                                            long count = totleFee / rule;

                                            subFee = count * value;
                                        } else if (ruleType == 2) {
                                            subFee = value;
                                        }

                                        if (subFee > currentShopDiscount.getDiscountTop()) {
                                            subFee = currentShopDiscount.getDiscountTop();
                                        }
                                    }

                                    resultFee = totleFee - subFee;
                                }


                                if (discountHandleType != null) {//1:四舍五入 2:只入不舍
                                    if (discountHandleType == 1) {
                                        if (discountPriceUnit == 1) {//1:分 2:角 3:元
                                            long temp = resultFee % 10;
                                            if (temp < 5) {
                                                resultFee = resultFee - temp;
                                            } else {
                                                if (resultFee > 10) {
                                                    resultFee = resultFee - temp + 10;
                                                }
                                            }
                                        } else if (discountPriceUnit == 2) {
                                            long temp = resultFee % 100;
                                            if (temp < 50) {
                                                resultFee = resultFee - temp;
                                            } else {
                                                if (resultFee > 100) {
                                                    resultFee = resultFee - temp + 100;
                                                }
                                            }

                                        }
                                    } else if (discountHandleType == 2) {//2:只入不舍
                                        if (discountPriceUnit == 1) {//1:分 2:角 3:元
                                            long temp = resultFee % 10;
                                            if (resultFee > 10) {
                                                resultFee = resultFee - temp + 10;
                                            }
                                        } else if (discountPriceUnit == 2) {
                                            long temp = resultFee % 100;
                                            if (resultFee > 100) {
                                                resultFee = resultFee - temp + 100;
                                            }

                                        }
                                    }

                                }
                                discountOrder.setNote(currentShopDiscount.getDiscountName());
                                discountOrder.setTotalFee(resultFee);

                                if (resultFee < 0) {
                                    discountOrder.setTotalFee(0l);
                                }
                                return discountOrder;
                            }
                        }
                    }


                } else {
                    //TODO
                    return null;
                }
            }
        }

        return null;

    }

    private boolean isPeriodAllow(String period){
        boolean periodAllow = false;
        ShopHoursConfig shopHoursConfig =
                shopHoursConfigMapper.selectByPrimaryKey(Integer.valueOf(period));

        Date endTime = shopHoursConfig.getEndTime();
        Date startTime = shopHoursConfig.getStartTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

        Date now = new Date();
        try {
            now = dateFormat.parse(dateFormat.format(now));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (now.after(startTime) && endTime.after(now)) {
            periodAllow = true;
        }

        return periodAllow;
    }
}
